import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Typography,
  Row,
  Col,
  Input,
  Select,
  message,
  Tooltip,
  Progress,
  Badge,
  Modal,
  Statistic,
  Dropdown
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  EyeOutlined,
  DeleteOutlined,
  DownloadOutlined,
  ExclamationCircleOutlined,
  RedoOutlined,
  SyncOutlined,
  GitlabOutlined,
  GithubOutlined,
  DatabaseOutlined,
  BranchesOutlined,
  ClockCircleOutlined,
  InfoCircleOutlined,
  LinkOutlined,
  ThunderboltOutlined,
  RobotOutlined,
  FileTextOutlined,
  MoreOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { 
  getUserScanTasks, 
  startTask, 
  cancelTask, 
  deleteScanTask,
  retryTask,
  checkTaskCredentials,
  ScanTaskResponse 
} from '../../services/api';
import { taskStatusPoller, TaskPollerInstance } from '../../utils/taskStatusPoller';
import './TaskList.css';

const { Title, Text } = Typography;
const { Option } = Select;

interface TaskListState {
  tasks: ScanTaskResponse[];
  loading: boolean;
  total: number;
  current: number;
  pageSize: number;
}

// 凭证状态缓存
interface CredentialStatusCache {
  [taskId: number]: {
    hasValidCredentials: boolean;
    gitCredentialValid: boolean;
    databaseCredentialValid: boolean;
    loading: boolean;
    lastChecked: number;
  };
}

const TaskList: React.FC = () => {
  const [state, setState] = useState<TaskListState>({
    tasks: [],
    loading: false,
    total: 0,
    current: 1,
    pageSize: 10
  });
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string | undefined>(undefined);
  const [taskTypeFilter, setTaskTypeFilter] = useState<string | undefined>(undefined);
  const [autoRefreshEnabled, setAutoRefreshEnabled] = useState<boolean>(true);
  const navigate = useNavigate();
  
  // 轮询实例管理
  const activePollers = useRef<Map<number, TaskPollerInstance>>(new Map());
  const lastPollingCheck = useRef<number>(0);
  
  // 凭证状态缓存
  const credentialStatusCache = useRef<CredentialStatusCache>({});

  /**
   * 判断任务是否需要凭证检查
   */
  const needsCredentialCheck = (task: ScanTaskResponse): boolean => {
    const taskType = task.taskType;
    // MANUAL_SQL 不需要凭证，其他类型都需要
    return taskType !== 'MANUAL_SQL';
  };

  /**
   * 检查任务凭证有效期（带缓存）
   */
  const checkTaskCredentialsWithCache = async (taskId: number): Promise<{
    hasValidCredentials: boolean;
    gitCredentialValid: boolean;
    databaseCredentialValid: boolean;
  }> => {
    const now = Date.now();
    const cached = credentialStatusCache.current[taskId];
    
    // 5分钟缓存
    if (cached && !cached.loading && (now - cached.lastChecked) < 5 * 60 * 1000) {
      return {
        hasValidCredentials: cached.hasValidCredentials,
        gitCredentialValid: cached.gitCredentialValid,
        databaseCredentialValid: cached.databaseCredentialValid
      };
    }

    // 设置加载状态
    credentialStatusCache.current[taskId] = {
      ...cached,
      loading: true,
      hasValidCredentials: false,
      gitCredentialValid: false,
      databaseCredentialValid: false,
      lastChecked: now
    };

    try {
      const response = await checkTaskCredentials(taskId);
      if (response.success) {
        const result = {
          hasValidCredentials: response.data.hasValidCredentials,
          gitCredentialValid: response.data.gitCredentialValid,
          databaseCredentialValid: response.data.databaseCredentialValid,
          loading: false,
          lastChecked: now
        };
        
        credentialStatusCache.current[taskId] = result;
        return result;
      }
    } catch (error) {
      console.warn(`检查任务${taskId}凭证失败:`, error);
    }

    // 失败时的默认值
    const defaultResult = {
      hasValidCredentials: false,
      gitCredentialValid: false,
      databaseCredentialValid: false,
      loading: false,
      lastChecked: now
    };
    
    credentialStatusCache.current[taskId] = defaultResult;
    return defaultResult;
  };

  /**
   * 判断任务是否可以重试（包含凭证检查）
   */
  const canRetryWithCredentials = (task: ScanTaskResponse): boolean => {
    // 基本条件：任务状态允许重试
    const statusAllowsRetry = ['FAILED', 'SUCCESS', 'CANCELLED'].includes(task.status);
    if (!statusAllowsRetry) {
      return false;
    }

    // 检查重试次数限制
    const currentRetryCount = task.retryCount || 0;
    const maxRetryCount = task.maxRetryCount || 3;
    if (currentRetryCount >= maxRetryCount) {
      return false;
    }

    // 对于需要凭证的任务，检查缓存的凭证状态
    if (needsCredentialCheck(task)) {
      const cached = credentialStatusCache.current[task.id];
      if (cached && !cached.loading) {
        return cached.hasValidCredentials;
      }
      // 如果没有缓存或正在加载，默认不可重试（稍后会检查）
      return false;
    }

    return true;
  };

  useEffect(() => {
    loadTasks();
  }, [state.current, state.pageSize]);

  // 组件卸载时清理所有轮询
  useEffect(() => {
    return () => {
      cleanupAllPollers();
    };
  }, []);

  // 当任务列表更新时，管理轮询实例
  useEffect(() => {
    if (autoRefreshEnabled) {
      manageTaskPolling();
    } else {
      cleanupAllPollers();
    }
  }, [state.tasks, autoRefreshEnabled]);

  /**
   * 清理所有轮询实例
   */
  const cleanupAllPollers = () => {
    console.log('TaskList: 清理所有轮询实例');
    activePollers.current.forEach((poller) => {
      poller.stop();
    });
    activePollers.current.clear();
  };

  /**
   * 管理任务轮询 - 为RUNNING状态的任务启动轮询
   */
  const manageTaskPolling = () => {
    const now = Date.now();
    
    // 防止过于频繁的轮询检查（每秒最多检查一次）
    if (now - lastPollingCheck.current < 1000) {
      return;
    }
    lastPollingCheck.current = now;

    const runningTasks = state.tasks.filter(task => task.status === 'RUNNING');
    const currentTaskIds = new Set(runningTasks.map(task => task.id));

    console.log(`TaskList: 发现 ${runningTasks.length} 个运行中的任务`, currentTaskIds);

    // 停止不再需要的轮询
    activePollers.current.forEach((poller, taskId) => {
      if (!currentTaskIds.has(taskId)) {
        console.log(`TaskList: 停止任务 ${taskId} 的轮询`);
        poller.stop();
        activePollers.current.delete(taskId);
      }
    });

    // 为新的运行中任务启动轮询
    runningTasks.forEach(task => {
      if (!activePollers.current.has(task.id)) {
        console.log(`TaskList: 为任务 ${task.id} 启动轮询`);
        
        const poller = taskStatusPoller.createPoller(task.id.toString(), {
          interval: 5000, // 每5秒轮询一次
          maxRetries: 3,
          onStatusChange: (updatedTask) => {
            console.log(`TaskList: 任务 ${task.id} 状态更新:`, updatedTask.status);
            updateTaskInList(updatedTask);
          },
          onComplete: (completedTask) => {
            console.log(`TaskList: 任务 ${task.id} 已完成:`, completedTask.status);
            updateTaskInList(completedTask);
            // 任务完成后停止轮询
            activePollers.current.delete(task.id);
          },
          onError: (error) => {
            console.warn(`TaskList: 任务 ${task.id} 轮询失败:`, error);
            // 错误时也要停止轮询
            activePollers.current.delete(task.id);
          }
        });

        activePollers.current.set(task.id, poller);
        poller.start();
      }
    });
  };

  /**
   * 更新任务列表中的单个任务
   */
  const updateTaskInList = (updatedTask: ScanTaskResponse) => {
    setState(prevState => ({
      ...prevState,
      tasks: prevState.tasks.map(task => 
        task.id === updatedTask.id ? { ...task, ...updatedTask } : task
      )
    }));
  };

  const loadTasks = async () => {
    try {
      setState(prev => ({ ...prev, loading: true }));
      
      // 从localStorage获取当前用户信息
      const userInfoStr = localStorage.getItem('userInfo');
      if (!userInfoStr) {
        message.error('用户信息不存在，请重新登录');
        setState(prev => ({ ...prev, loading: false }));
        return;
      }
      
      const userInfo = JSON.parse(userInfoStr);
      console.log('当前用户信息:', userInfo); // 调试日志
      
      // 对于管理员和普通用户，都查询当前用户的ID（后端会根据用户角色返回相应的数据）
      // 管理员会看到所有任务，普通用户只会看到自己的任务
      const response = await getUserScanTasks(userInfo.id, state.current, state.pageSize);
      console.log('API响应:', response); // 调试日志
      
      if (response.success) {
        setState(prev => ({
          ...prev,
          tasks: response.data.records || [],
          total: response.data.total || 0,
          loading: false
        }));
      } else {
        console.error('API返回错误:', response);
        message.error(response.message || '加载任务列表失败');
        setState(prev => ({ ...prev, loading: false }));
      }
    } catch (error: any) {
      console.error('加载任务失败:', error);
      message.error(error.message || '加载任务列表失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  const handleTaskAction = async (action: string, taskId: number) => {
    try {
      // 对于重试操作，先检查凭证和显示确认对话框
      if (action === 'retry') {
        const task = state.tasks.find(t => t.id === taskId);
        if (!task) return;

        // 检查凭证有效期
        if (needsCredentialCheck(task)) {
          try {
            const credentialStatus = await checkTaskCredentialsWithCache(taskId);
            if (!credentialStatus.hasValidCredentials) {
              message.error('用户凭证已过期，无法重试任务。请重新授权后再试。');
              return;
            }
          } catch (error) {
            console.error('检查凭证失败:', error);
            message.error('检查凭证失败，请稍后重试');
            return;
          }
        }

        // 显示重试确认对话框
        const confirmed = await new Promise<boolean>((resolve) => {
          Modal.confirm({
            title: '确认重试任务',
            content: (
              <div>
                <p>重试将重新执行整个任务，并覆盖原有的执行结果。</p>
                <p>当前重试次数: {task.retryCount || 0}/{task.maxRetryCount || 3}</p>
                <p>确定要继续吗？</p>
              </div>
            ),
            okText: '确认重试',
            cancelText: '取消',
            onOk: () => resolve(true),
            onCancel: () => resolve(false)
          });
        });

        if (!confirmed) {
          return;
        }
      }

      let response: any;
      switch (action) {
        case 'start':
          response = await startTask(taskId);
          message.success('任务启动请求已提交，正在后台执行...');
          // 立即更新任务状态为RUNNING（乐观更新）
          setState(prevState => ({
            ...prevState,
            tasks: prevState.tasks.map(task => 
              task.id === taskId ? { ...task, status: 'RUNNING', progress: 0 } : task
            )
          }));
          break;
        case 'cancel':
          response = await cancelTask(taskId);
          message.success('任务已取消');
          break;
        case 'delete':
          Modal.confirm({
            title: '确认删除',
            content: '确定要删除这个任务吗？删除后无法恢复。',
            icon: <ExclamationCircleOutlined />,
            onOk: async () => {
              await deleteScanTask(taskId);
              message.success('任务删除成功');
              loadTasks();
            }
          });
          return;
        case 'retry':
          response = await retryTask(taskId);
          if (response && response.success) {
            message.success('任务重试成功，正在后台执行...');
            // 立即更新任务状态为RUNNING（乐观更新）
            setState(prevState => ({
              ...prevState,
              tasks: prevState.tasks.map(task => 
                task.id === taskId ? { 
                  ...task, 
                  status: 'RUNNING', 
                  progress: 0, 
                  errorMessage: undefined,
                  retryCount: response.data.retryCount || (task.retryCount || 0) + 1
                } : task
              )
            }));
          } else {
            message.error(response?.message || '重试任务失败');
          }
          
          // 清除凭证缓存，下次会重新检查
          delete credentialStatusCache.current[taskId];
          break;
        default:
          return;
      }
      
      // 对于启动和重试操作，不需要立即重新加载，让轮询机制处理更新
      if (action !== 'start' && action !== 'retry') {
        loadTasks();
      }
    } catch (error: any) {
      console.error('任务操作失败:', error);
      message.error(error.message || '操作失败');
      // 如果启动失败，恢复任务状态
      if (action === 'start' || action === 'retry') {
        loadTasks();
      }
    }
  };

  const getStatusTag = (status: string) => {
    const statusConfig = {
      PENDING: { color: 'default', text: '待执行' },
      RUNNING: { color: 'processing', text: '执行中' },
      COMPLETED: { color: 'success', text: '已完成' },
      FAILED: { color: 'error', text: '失败' },
      CANCELLED: { color: 'warning', text: '已取消' }
    };
    
    const config = statusConfig[status as keyof typeof statusConfig] || 
                  { color: 'default', text: status };
    
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getTaskTypeTag = (taskType: string) => {
    const typeConfig = {
      PROJECT_SCAN: { color: 'blue', text: '项目扫描', icon: <FileTextOutlined /> },
      GIT_SOURCE_SCAN: { color: 'green', text: 'Git源码', icon: <GithubOutlined /> },
      DATABASE_DDL_SCAN: { color: 'orange', text: '数据库DDL', icon: <DatabaseOutlined /> },
      MIXED_SCAN: { color: 'purple', text: '混合扫描', icon: <ThunderboltOutlined /> },
      MANUAL_SQL: { color: 'purple', text: '手动SQL', icon: <FileTextOutlined /> }
    };
    
    const config = typeConfig[taskType as keyof typeof typeConfig] || 
                  { color: 'default', text: taskType, icon: <FileTextOutlined /> };
    
    return (
      <Tag color={config.color} icon={config.icon} style={{ marginRight: 0 }}>
        {config.text}
      </Tag>
    );
  };

  // 解析配置信息
  const parseTaskConfig = (configJson?: string) => {
    if (!configJson) return null;
    try {
      return JSON.parse(configJson);
    } catch {
      return null;
    }
  };

  // 获取Git平台图标
  const getGitPlatformIcon = (url: string) => {
    if (url?.includes('gitlab')) return <GitlabOutlined style={{ color: '#FC6D26' }} />;
    if (url?.includes('github')) return <GithubOutlined style={{ color: '#333' }} />;
    return <LinkOutlined style={{ color: '#1890ff' }} />;
  };

  // 格式化时间duration
  const formatDuration = (startTime?: string, endTime?: string) => {
    if (!startTime) return '-';
    if (!endTime) {
      // 如果没有结束时间，计算到现在的时间
      const start = new Date(startTime);
      const now = new Date();
      const duration = Math.floor((now.getTime() - start.getTime()) / 1000);
      return formatSeconds(duration) + ' (运行中)';
    }
    const start = new Date(startTime);
    const end = new Date(endTime);
    const duration = Math.floor((end.getTime() - start.getTime()) / 1000);
    return formatSeconds(duration);
  };

  const formatSeconds = (seconds: number) => {
    if (seconds < 60) return `${seconds}秒`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${hours}小时${minutes}分`;
  };

  // 获取扫描引擎标签 - 优先使用后端增强字段
  const getScanEngineTag = (record: ScanTaskResponse) => {
    // 优先使用后端提供的增强显示字段
    if (record.analysisEngineDisplay) {
      const isAI = record.analysisEngineDisplay.includes('AI');
      return (
        <Tag 
          color={isAI ? 'purple' : 'blue'} 
          icon={isAI ? <RobotOutlined /> : <ThunderboltOutlined />}
          style={{ fontSize: '11px', padding: '0 4px' }}
        >
          {record.analysisEngineDisplay}
        </Tag>
      );
    }
    
    // 后备方案：解析config配置
    const config = record.config || parseTaskConfig(record.configJson);
    const analysisEngine = config?.analysisEngine || 'RULE_BASED';
    
    // 支持多种引擎值的映射
    if (analysisEngine === 'LLM_BASED' || analysisEngine === 'AI_ANALYSIS' || analysisEngine === 'AI') {
      return <Tag color="purple" icon={<RobotOutlined />} style={{ fontSize: '11px', padding: '0 4px' }}>AI引擎</Tag>;
    }
    return <Tag color="blue" icon={<ThunderboltOutlined />} style={{ fontSize: '11px', padding: '0 4px' }}>规则引擎</Tag>;
  };

  // 渲染Git信息
  const renderGitInfo = (record: ScanTaskResponse) => {
    const config = parseTaskConfig(record.configJson);
    const gitUrl = config?.gitRepositoryUrl;
    const branchName = record.branchName;
    
    if (!gitUrl && !branchName) {
      return <Text type="secondary">-</Text>;
    }

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {gitUrl && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            {getGitPlatformIcon(gitUrl)}
            <Tooltip title={gitUrl}>
              <Button 
                type="link" 
                size="small" 
                onClick={() => window.open(gitUrl, '_blank')}
                style={{ padding: 0, height: 'auto', fontSize: '12px' }}
              >
                {gitUrl.split('/').pop()?.replace('.git', '') || '仓库链接'}
              </Button>
            </Tooltip>
          </div>
        )}
        {branchName && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <BranchesOutlined style={{ color: '#52c41a', fontSize: '12px' }} />
            <Text style={{ fontSize: '12px' }}>{branchName}</Text>
          </div>
        )}
      </div>
    );
  };

  // 渲染数据库信息
  const renderDatabaseInfo = (record: ScanTaskResponse) => {
    const config = parseTaskConfig(record.configJson);
    const enableDatabaseScan = config?.enableDatabaseScan;
    const databaseHost = config?.databaseHost;
    const databaseName = config?.databaseName;
    
    if (!enableDatabaseScan && !databaseHost) {
      return <Text type="secondary">-</Text>;
    }

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {databaseHost && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <DatabaseOutlined style={{ color: '#fa8c16', fontSize: '12px' }} />
            <Text style={{ fontSize: '12px' }}>
              {databaseHost}{config?.databasePort ? `:${config.databasePort}` : ''}
            </Text>
          </div>
        )}
        {databaseName && (
          <Text style={{ fontSize: '12px', color: '#666' }}>
            库: {databaseName}
          </Text>
        )}
      </div>
    );
  };

  const getActionMenuItems = (record: ScanTaskResponse) => {
    const userInfo = (() => {
      try {
        const userInfoStr = localStorage.getItem('userInfo');
        return userInfoStr ? JSON.parse(userInfoStr) : null;
      } catch {
        return null;
      }
    })();

    const isAdmin = userInfo?.role === 'ADMIN';
    const isOwner = userInfo?.id === record.userId;
    const canOperate = isAdmin || isOwner;

    const items: any[] = [
      {
        key: 'view',
        label: '查看详情',
        icon: <EyeOutlined />,
        onClick: () => navigate(`/tasks/${record.id}`)
      }
    ];

    if (!canOperate) {
      return items;
    }

    // 检查是否可以重试（包含凭证检查）
    const canRetryExtended = canRetryWithCredentials(record);
    const cached = credentialStatusCache.current[record.id];
    const isCredentialLoading = cached?.loading || false;

    // 基于任务状态的操作
    if (record.status === 'PENDING') {
      items.push(
        {
          key: 'start',
          label: '启动任务',
          icon: <PlayCircleOutlined style={{ color: '#52c41a' }} />,
          onClick: () => handleTaskAction('start', record.id)
        },
        {
          key: 'edit',
          label: '编辑任务',
          icon: <InfoCircleOutlined />,
          onClick: () => {
            // TODO: 实现编辑功能
            message.info('编辑功能开发中...');
          }
        }
      );
    }

    if (record.status === 'RUNNING') {
      items.push({
        key: 'cancel',
        label: '取消任务',
        icon: <PauseCircleOutlined style={{ color: '#faad14' }} />,
        onClick: () => handleTaskAction('cancel', record.id)
      });
    }

    if (record.status === 'SUCCESS') {
      items.push(
        {
          key: 'download',
          label: '下载报告',
          icon: <DownloadOutlined style={{ color: '#1890ff' }} />,
          onClick: () => {
            // TODO: 实现下载功能
            message.info('下载功能开发中...');
          }
        },
        {
          key: 'view-report',
          label: '查看报告',
          icon: <FileTextOutlined style={{ color: '#722ed1' }} />,
          onClick: () => navigate(`/tasks/${record.id}`)
        }
      );
    }

    // 扩展的重试功能 - 支持多种状态和凭证检查
    if (record.status === 'FAILED') {
      // 传统的FAILED状态重试
      if (record.canRetry || canRetryExtended) {
        items.push({
          key: 'retry',
          label: isCredentialLoading ? '检查凭证中...' : '重试任务',
          icon: <RedoOutlined style={{ color: isCredentialLoading ? '#faad14' : '#1890ff' }} />,
          disabled: isCredentialLoading,
          onClick: () => handleTaskAction('retry', record.id)
        });
      }
      
      items.push({
        key: 'view-error',
        label: '查看错误',
        icon: <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />,
        onClick: () => {
          if (record.errorMessage) {
            Modal.info({
              title: `任务执行错误 - ${record.taskName}`,
              content: (
                <div style={{ maxHeight: '300px', overflow: 'auto', padding: '8px 0' }}>
                  <Text code style={{ whiteSpace: 'pre-wrap', fontSize: '12px' }}>
                    {record.errorMessage}
                  </Text>
                </div>
              ),
              width: 600,
              okText: '确定'
            });
          } else {
            message.info('暂无错误信息');
          }
        }
      });
    }

    // 新增：对于已完成、已取消状态的重新执行功能
    if (['SUCCESS', 'CANCELLED'].includes(record.status) && canRetryExtended) {
      const needsCredentials = needsCredentialCheck(record);
      const hasValidCredentials = !needsCredentials || (cached && cached.hasValidCredentials);
      
      items.push({
        key: 'retry',
        label: isCredentialLoading ? '检查凭证中...' : '重新执行',
        icon: <RedoOutlined style={{ 
          color: isCredentialLoading ? '#faad14' : 
                 (!needsCredentials || hasValidCredentials) ? '#1890ff' : '#d9d9d9'
        }} />,
        disabled: isCredentialLoading || (needsCredentials && !hasValidCredentials),
        onClick: () => {
          if (needsCredentials && !hasValidCredentials) {
            message.warning('用户凭证已过期，无法重新执行任务');
            return;
          }
          handleTaskAction('retry', record.id);
        }
      });

      // 预检查凭证状态（如果需要且未检查过）
      if (needsCredentials && !cached) {
        // 异步检查凭证，但不阻塞UI
        checkTaskCredentialsWithCache(record.id).catch(() => {
          // 忽略错误，用户点击时会再次检查
        });
      }
    }

    // 通用操作
    items.push(
      {
        type: 'divider'
      },
      {
        key: 'copy-link',
        label: '复制链接',
        icon: <LinkOutlined />,
        onClick: () => {
          const link = `${window.location.origin}/tasks/${record.id}`;
          navigator.clipboard.writeText(link).then(() => {
            message.success('链接已复制到剪贴板');
          }).catch(() => {
            message.error('复制失败');
          });
        }
      }
    );

    // 删除操作（仅非运行状态任务）
    if (['SUCCESS', 'FAILED', 'CANCELLED', 'PENDING'].includes(record.status)) {
      items.push({
        key: 'delete',
        label: '删除任务',
        icon: <DeleteOutlined style={{ color: '#ff4d4f' }} />,
        danger: true,
        onClick: () => handleTaskAction('delete', record.id)
      });
    }

    return items;
  };

  const columns: ColumnsType<ScanTaskResponse> = [
    {
      title: '任务名称',
      dataIndex: 'taskName',
      key: 'taskName',
      width: 200,
      render: (text, record) => (
        <Button 
          type="link" 
          onClick={() => navigate(`/tasks/${record.id}`)}
          style={{ 
            padding: 0, 
            height: 'auto', 
            fontWeight: 500, 
            textAlign: 'left',
            whiteSpace: 'normal',
            wordBreak: 'break-all',
            lineHeight: '1.4',
            display: '-webkit-box',
            WebkitBoxOrient: 'vertical',
            WebkitLineClamp: 2,
            overflow: 'hidden',
            maxHeight: '2.8em'
          }}
        >
          {text}
        </Button>
      )
    },
    {
      title: '任务类型',
      dataIndex: 'taskType',
      key: 'taskType',
      width: 100,
      render: (taskType) => getTaskTypeTag(taskType)
    },
    {
      title: '扫描引擎',
      key: 'scanEngine',
      width: 90,
      render: (_, record) => getScanEngineTag(record)
    },
    {
      title: 'SQL源信息',
      key: 'sqlSource',
      width: 200,
      render: (_, record) => {
        // 优先使用后端提供的增强显示字段
        if (record.dataSourceDisplay && record.dataSourceDisplay.trim() !== '') {
          const display = record.dataSourceDisplay;
          
          if (display.includes(':') && (display.includes('ORACLE') || display.includes('MYSQL') || display.includes('DATABASE'))) {
            // 数据库类型 - 分三行显示
            const parts = display.split(': ');
            if (parts.length >= 2) {
              const dbType = parts[0]; // 如 "ORACLE"
              const connectionInfo = parts[1]; // 如 "168.63.18.127:1521/servdb"
              
              let host = '', port = '', database = '';
              if (connectionInfo.includes(':') && connectionInfo.includes('/')) {
                const [hostPort, db] = connectionInfo.split('/');
                const [hostPart, portPart] = hostPort.split(':');
                host = hostPart;
                port = portPart;
                database = db;
              }
              
              return (
                <div className="sql-source-info">
                  <div className="source-header">
                    <DatabaseOutlined style={{ color: '#fa8c16', fontSize: '12px' }} />
                    <span className="source-title">{dbType}</span>
                  </div>
                  {host && (
                    <div className="source-detail">
                      {host}{port && `:${port}`}
                    </div>
                  )}
                  {database && (
                    <div className="source-detail">
                      {database}
                    </div>
                  )}
                </div>
              );
            }
            
            // 降级处理：如果解析失败，使用原始显示
            return (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <DatabaseOutlined style={{ color: '#fa8c16' }} />
                <span style={{ fontSize: '12px' }}>{display}</span>
              </div>
            );
          } else if (display.includes('GITLAB') || display.includes('GITHUB') || display.includes('GITEE') || display.includes('Git')) {
            // Git类型 - 分两行显示
            let platform = '';
            let repoName = '';
            
            if (display.includes('GITLAB:')) {
              platform = 'GITLAB';
              repoName = display.replace('GITLAB: ', '').trim();
            } else if (display.includes('GITHUB:')) {
              platform = 'GITHUB'; 
              repoName = display.replace('GITHUB: ', '').trim();
            } else if (display.includes('GITEE:')) {
              platform = 'GITEE';
              repoName = display.replace('GITEE: ', '').trim();
            } else {
              // 其他Git格式
              const parts = display.split(': ');
              platform = parts[0] || 'Git';
              repoName = parts[1] || parts[0];
            }
            
            const icon = platform === 'GITLAB' ? 
                        <GitlabOutlined style={{ color: '#FC6D26', fontSize: '12px' }} /> :
                        platform === 'GITHUB' ? 
                        <GithubOutlined style={{ color: '#333', fontSize: '12px' }} /> :
                        platform === 'GITEE' ?
                        <GithubOutlined style={{ color: '#c71d23', fontSize: '12px' }} /> :
                        <GithubOutlined style={{ color: '#333', fontSize: '12px' }} />;
            
            return (
              <div className="sql-source-info">
                <div className="source-header">
                  {icon}
                  <span className="source-title">{platform}</span>
                </div>
                {repoName && (
                  <div className="source-detail">
                    {repoName}
                  </div>
                )}
              </div>
            );
          } else if (display === '手动SQL输入') {
            // 手动SQL类型  
            return (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <FileTextOutlined style={{ color: '#722ed1' }} />
                <span style={{ fontSize: '12px' }}>{display}</span>
              </div>
            );
          } else {
            // 其他类型，直接显示
            return <span style={{ fontSize: '12px' }}>{display}</span>;
          }
        }

        // 后备方案：使用原有的复杂逻辑
        const config = record.config || parseTaskConfig(record.configJson);
        
        // 从描述中提取仓库和分支信息
        const extractRepoInfoFromDescription = (description: string) => {
          if (!description) return { repoName: null, branch: null };
          
          const repoMatch = description.match(/扫描仓库[:：]([^\n\r]+)/);
          const branchMatch = description.match(/分支[:：]([^\n\r]+)/);
          
          return {
            repoName: repoMatch ? repoMatch[1].trim() : null,
            branch: branchMatch ? branchMatch[1].trim() : null
          };
        };
        
        const descriptionInfo = extractRepoInfoFromDescription(record.description || '');
        
        // 尝试多个可能的字段名和数据结构
        const gitUrl = config?.repositoryUrl || config?.gitRepositoryUrl || config?.gitUrl || 
                      config?.gitConfig?.repositoryUrl || config?.git?.repositoryUrl;
        const branch = record.branchName || config?.branch || config?.gitConfig?.branch || 
                      config?.git?.branch || config?.gitBranch || descriptionInfo.branch;
        const repoName = descriptionInfo.repoName || (gitUrl ? gitUrl.split('/').pop()?.replace('.git', '') : null);
        
        const databaseHost = config?.databaseHost || config?.host || config?.dbConfig?.host ||
                            config?.database?.host;
        const databaseName = config?.databaseName || config?.database || config?.dbConfig?.database ||
                            config?.database?.name;
        
        // Git 任务类型检查
        if (record.taskType?.includes('GIT') || record.taskType === 'PROJECT_SCAN') {
          if (gitUrl) {
            const repoName = gitUrl.split('/').pop()?.replace('.git', '') || 'Git仓库';
            const platform = gitUrl.includes('gitlab') ? 'GITLAB' : 
                           gitUrl.includes('github') ? 'GITHUB' : 
                           gitUrl.includes('gitee') ? 'GITEE' : 'Git';
            
            return (
              <div className="sql-source-info">
                <div className="source-header">
                  {getGitPlatformIcon(gitUrl)}
                  <span className="source-title">{platform}</span>
                </div>
                <div className="source-detail">
                  {repoName}
                </div>
              </div>
            );
          }
          
          // 如果有从描述中提取的仓库名称
          if (repoName) {
            return (
              <div className="sql-source-info">
                <div className="source-header">
                  <GithubOutlined style={{ color: '#333', fontSize: '12px' }} />
                  <span className="source-title">Git</span>
                </div>
                <div className="source-detail">
                  {repoName}
                </div>
              </div>
            );
          }
          
          // 如果有项目名称
          if (record.projectName) {
            return (
              <div className="sql-source-info">
                <div className="source-header">
                  <GithubOutlined style={{ color: '#333', fontSize: '12px' }} />
                  <span className="source-title">Git</span>
                </div>
                <div className="source-detail">
                  {record.projectName}
                </div>
              </div>
            );
          }
          
          // 最后的后备方案
          return (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <GithubOutlined style={{ color: '#333', fontSize: '12px' }} />
              <span style={{ fontSize: '12px' }}>Git源码</span>
            </div>
          );
        }
        
        // 数据库任务类型检查 - 分三行显示
        if (record.taskType?.includes('DATABASE') || databaseHost) {
          const dbType = record.sourceDbType || 
                        (record.taskType?.includes('DATABASE') ? 
                          (record.description?.includes('MySQL') ? 'MYSQL' : 
                           record.description?.includes('Oracle') ? 'ORACLE' : 'DATABASE') 
                          : 'DATABASE');
          
          return (
            <div className="sql-source-info">
              <div className="source-header">
                <DatabaseOutlined style={{ color: '#fa8c16', fontSize: '12px' }} />
                <span className="source-title">{dbType}</span>
              </div>
              {databaseHost && (
                <div className="source-detail">
                  {databaseHost}{config?.databasePort ? `:${config.databasePort}` : ''}
                </div>
              )}
              {databaseName && (
                <div className="source-detail">
                  {databaseName}
                </div>
              )}
            </div>
          );
        }
        
        // 混合扫描任务
        if (record.taskType === 'MIXED_SCAN') {
          const parts = [];
          if (gitUrl || repoName || record.projectName) {
            parts.push('Git源码');
          }
          if (databaseHost || config?.enableDatabaseScan) {
            parts.push('数据库DDL');
          }
          
          if (parts.length > 0) {
            return (
              <div style={{ fontSize: '12px' }}>
                <ThunderboltOutlined style={{ color: '#722ed1', marginRight: 4 }} />
                {parts.join(' + ')}
              </div>
            );
          }
        }
        
        // 手动SQL类型
        if (record.taskType === 'MANUAL_SQL') {
          return (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <FileTextOutlined style={{ color: '#722ed1' }} />
              <span style={{ fontSize: '12px' }}>手动SQL输入</span>
            </div>
          );
        }
        
        return <Text type="secondary" style={{ fontSize: '12px' }}>-</Text>;
      }
    },
    {
      title: '创建者',
      dataIndex: 'username',
      key: 'username',
      width: 80,
      render: (username) => (
        <span style={{ fontSize: '12px' }}>{username || '-'}</span>
      )
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 110,
      render: (startTime) => (
        startTime ? (
          <span style={{ fontSize: '12px' }}>
            {new Date(startTime).toLocaleString('zh-CN', {
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            })}
          </span>
        ) : <Text type="secondary" style={{ fontSize: '12px' }}>-</Text>
      )
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 110,
      render: (endTime) => (
        endTime ? (
          <span style={{ fontSize: '12px' }}>
            {new Date(endTime).toLocaleString('zh-CN', {
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            })}
          </span>
        ) : <Text type="secondary" style={{ fontSize: '12px' }}>-</Text>
      )
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status, record) => {
        const isPolling = activePollers.current.has(record.id);
        const canRetryExtended = canRetryWithCredentials(record);
        const needsCredentials = needsCredentialCheck(record);
        const cached = credentialStatusCache.current[record.id];
        
        // 只对可重试且需要凭证的任务显示凭证状态
        const shouldShowCredentialStatus = ['SUCCESS', 'CANCELLED', 'FAILED'].includes(status) && 
                                          needsCredentials && canRetryExtended;
        
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            {getStatusTag(status)}
            {isPolling && (
              <SyncOutlined spin style={{ color: '#1890ff', fontSize: 12 }} />
            )}
            {shouldShowCredentialStatus && (
              <Tooltip 
                title={
                  cached?.loading ? '正在检查凭证状态...' :
                  cached?.hasValidCredentials ? '凭证有效，可重新执行' :
                  cached ? '凭证已过期，无法重新执行' :
                  '点击操作菜单检查凭证状态'
                }
              >
                {cached?.loading ? (
                  <SyncOutlined spin style={{ color: '#faad14', fontSize: 10 }} />
                ) : cached?.hasValidCredentials ? (
                  <span style={{ color: '#52c41a', fontSize: 10 }}>🔑</span>
                ) : cached ? (
                  <span style={{ color: '#ff4d4f', fontSize: 10 }}>🔒</span>
                ) : (
                  <span style={{ color: '#d9d9d9', fontSize: 10 }}>❓</span>
                )}
              </Tooltip>
            )}
          </div>
        );
      }
    },
    {
      title: '当前进度',
      dataIndex: 'progress',
      key: 'progress',
      width: 120,
      render: (progress, record) => {
        const isPolling = activePollers.current.has(record.id);
        
        if (record.status === 'RUNNING') {
          return (
            <Progress 
              percent={progress || 0} 
              size="small" 
              status={isPolling ? 'active' : 'normal'}
              strokeWidth={6}
              format={(percent) => `${percent}%`}
            />
          );
        }
        if (record.status === 'SUCCESS') {
          return <Progress percent={100} size="small" status="success" strokeWidth={6} />;
        }
        if (record.status === 'FAILED') {
          return <Progress percent={progress || 0} size="small" status="exception" strokeWidth={6} />;
        }
        return <Text type="secondary" style={{ fontSize: '12px' }}>-</Text>;
      }
    },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        <Dropdown
          menu={{ 
            items: getActionMenuItems(record),
            onClick: ({ key, domEvent }) => {
              domEvent.stopPropagation();
            }
          }}
          trigger={['click']}
          placement="bottomRight"
        >
          <Button
            size="small"
            icon={<MoreOutlined />}
            onClick={(e) => e.stopPropagation()}
          >
            操作
          </Button>
        </Dropdown>
      )
    }
  ];

  const filteredTasks = state.tasks.filter(task => {
    if (searchText && !task.taskName.toLowerCase().includes(searchText.toLowerCase())) {
      return false;
    }
    if (statusFilter && task.status !== statusFilter) {
      return false;
    }
    if (taskTypeFilter && task.taskType !== taskTypeFilter) {
      return false;
    }
    return true;
  });

  return (
    <div className="task-list">
      <div className="page-header">
        <Title level={3}>
          任务管理
          {(() => {
            try {
              const userInfoStr = localStorage.getItem('userInfo');
              if (userInfoStr) {
                const userInfo = JSON.parse(userInfoStr);
                return userInfo.role === 'ADMIN' 
                  ? <Tag color="gold" style={{ marginLeft: 8 }}>管理员视图 - 全部任务</Tag>
                  : <Tag color="blue" style={{ marginLeft: 8 }}>我的任务</Tag>;
              }
            } catch (e) {
              // ignore
            }
            return null;
          })()}
        </Title>
      </div>

      {/* 操作栏 */}
      <Card className="filter-card" bodyStyle={{ padding: '16px 24px' }}>
        <Row gutter={[16, 16]} align="middle">
          <Col flex="auto">
            <Row gutter={[12, 8]} align="middle">
              <Col>
                <Input
                  placeholder="搜索任务名称"
                  prefix={<SearchOutlined />}
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  style={{ width: 200 }}
                  allowClear
                />
              </Col>
              <Col>
                <Select
                  placeholder="任务状态"
                  value={statusFilter}
                  onChange={(value) => setStatusFilter(value)}
                  style={{ width: 120 }}
                  allowClear
                >
                  <Option value="PENDING">待执行</Option>
                  <Option value="RUNNING">执行中</Option>
                  <Option value="SUCCESS">已完成</Option>
                  <Option value="FAILED">失败</Option>
                  <Option value="CANCELLED">已取消</Option>
                </Select>
              </Col>
              <Col>
                <Select
                  placeholder="任务类型"
                  value={taskTypeFilter}
                  onChange={(value) => setTaskTypeFilter(value)}
                  style={{ width: 130 }}
                  allowClear
                >
                  <Option value="PROJECT_SCAN">项目扫描</Option>
                  <Option value="GIT_SOURCE_SCAN">Git源码</Option>
                  <Option value="DATABASE_DDL_SCAN">数据库DDL</Option>
                  <Option value="MANUAL_SQL">手动SQL</Option>
                </Select>
              </Col>
            </Row>
          </Col>
          <Col>
            <Space size="middle">
              <Tooltip title={autoRefreshEnabled ? '点击关闭自动刷新' : '点击开启自动刷新'}>
                <Button
                  icon={<SyncOutlined spin={autoRefreshEnabled && activePollers.current.size > 0} />}
                  type={autoRefreshEnabled ? 'primary' : 'default'}
                  onClick={() => setAutoRefreshEnabled(!autoRefreshEnabled)}
                  size="small"
                  className="auto-refresh-button"
                >
                  {autoRefreshEnabled ? `自动刷新 (${activePollers.current.size})` : '自动刷新'}
                </Button>
              </Tooltip>
              <Button
                icon={<ReloadOutlined />}
                onClick={loadTasks}
                loading={state.loading}
                className="refresh-button"
              >
                刷新
              </Button>
              <Button
                type="primary"
                onClick={() => navigate('/create-task')}
                className="create-task-button"
              >
                创建任务
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card size="small">
            <Statistic 
              title="待执行任务" 
              value={filteredTasks.filter(t => t.status === 'PENDING').length} 
              prefix={<ClockCircleOutlined style={{ color: '#faad14' }} />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic 
              title="执行中" 
              value={filteredTasks.filter(t => t.status === 'RUNNING').length} 
              prefix={<SyncOutlined style={{ color: '#1890ff' }} />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic 
              title="已完成" 
              value={filteredTasks.filter(t => t.status === 'SUCCESS').length} 
              prefix={<Badge status="success" />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic 
              title="失败/取消" 
              value={filteredTasks.filter(t => ['FAILED', 'CANCELLED'].includes(t.status)).length} 
              prefix={<Badge status="error" />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 任务列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={filteredTasks}
          rowKey="id"
          loading={state.loading}
          pagination={{
            current: state.current,
            pageSize: state.pageSize,
            total: state.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
            onChange: (page, size) => {
              setState(prev => ({
                ...prev,
                current: page,
                pageSize: size || 10
              }));
            },
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          scroll={{ x: 1100, y: 600 }}
          className="task-table"
          rowClassName={(record) => {
            if (record.status === 'RUNNING') return 'task-row-running';
            if (record.status === 'FAILED') return 'task-row-failed';
            if (record.status === 'SUCCESS') return 'task-row-success';
            return '';
          }}
        />
      </Card>
    </div>
  );
};

export default TaskList;